import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  ScrollView,
  Alert,
  PermissionsAndroid,
  Platform,
} from 'react-native';
import SpeechEngine from 'react-native-speech-engine';

interface SpeechRecognitionResult {
  transcript: string;
  isFinal: boolean;
}

interface SpeechError {
  message: string;
}

const App = () => {
  const [isListening, setIsListening] = useState<boolean>(false);
  const [isSpeaking, setIsSpeaking] = useState<boolean>(false);
  const [recognizedText, setRecognizedText] = useState<string>('');
  const [partialText, setPartialText] = useState<string>('');
  const [isAvailable, setIsAvailable] = useState<boolean>(false);

  useEffect(() => {
    // 检查语音识别可用性
    checkAvailability();

    // 请求Android权限
    if (Platform.OS === 'android') {
      requestAndroidPermissions();
    }

    // 设置事件监听器
    setupEventListeners();

    return () => {
      // 清理监听器
      SpeechEngine.removeAllListeners();
    };
  }, []);

  const checkAvailability = async (): Promise<void> => {
    try {
      const available = await SpeechEngine.isSpeechRecognitionAvailable();
      setIsAvailable(available);
    } catch (error) {
      console.error('Error checking availability:', error);
    }
  };

  const requestAndroidPermissions = async (): Promise<void> => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
        {
          title: '麦克风权限',
          message: '应用需要访问麦克风来进行语音识别',
          buttonNeutral: '稍后询问',
          buttonNegative: '取消',
          buttonPositive: '确定',
        }
      );

      if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
        Alert.alert('权限被拒绝', '需要麦克风权限才能使用语音识别功能');
      }
    } catch (err) {
      console.warn(err);
    }
  };

  const setupEventListeners = (): void => {
    // 语音识别事件
    SpeechEngine.onSpeechRecognitionStart(() => {
      console.log('语音识别开始');
      setIsListening(true);
      setPartialText('');
    });

    SpeechEngine.onSpeechRecognitionEnd(() => {
      console.log('语音识别结束');
      setIsListening(false);
      setPartialText('');
    });

    SpeechEngine.onSpeechRecognitionResults((results: SpeechRecognitionResult[]) => {
      console.log('识别结果:', results);
      if (results && results.length > 0) {
        const result = results[0];
        if (result.isFinal) {
          setRecognizedText(result.transcript);
          setPartialText('');
        } else {
          setPartialText(result.transcript);
        }
      }
    });

    SpeechEngine.onSpeechRecognitionError((error: SpeechError) => {
      console.error('语音识别错误:', error);
      setIsListening(false);
      Alert.alert('语音识别错误', error.message);
    });

    // 文字转语音事件
    SpeechEngine.onTextToSpeechStart(() => {
      console.log('开始朗读');
      setIsSpeaking(true);
    });

    SpeechEngine.onTextToSpeechFinish(() => {
      console.log('朗读完成');
      setIsSpeaking(false);
    });

    SpeechEngine.onTextToSpeechError((error: string) => {
      console.error('朗读错误:', error);
      setIsSpeaking(false);
      Alert.alert('朗读错误', error);
    });
  };

  const startListening = async (): Promise<void> => {
    try {
      if (!isAvailable) {
        Alert.alert('不可用', '语音识别在此设备上不可用');
        return;
      }

      await SpeechEngine.startSpeechRecognition({
        locale: 'zh-CN', // 中文识别
        partialResults: true,
      });
    } catch (error) {
      console.error('开始录音错误:', error);
      Alert.alert('错误', '无法开始语音识别');
    }
  };

  const stopListening = async (): Promise<void> => {
    try {
      await SpeechEngine.stopSpeechRecognition();
    } catch (error) {
      console.error('停止录音错误:', error);
    }
  };

  const cancelListening = async (): Promise<void> => {
    try {
      await SpeechEngine.cancelSpeechRecognition();
      setPartialText('');
    } catch (error) {
      console.error('取消录音错误:', error);
    }
  };

  const speakText = async (text: string): Promise<void> => {
    try {
      if (!text.trim()) {
        Alert.alert('提示', '请先输入或识别一些文字');
        return;
      }

      await SpeechEngine.speak(text, {
        language: 'zh-CN',
        pitch: 1.0,
        rate: 1.0,
        volume: 1.0,
      });
    } catch (error) {
      console.error('朗读错误:', error);
      Alert.alert('错误', '无法朗读文字');
    }
  };

  const stopSpeaking = async (): Promise<void> => {
    try {
      await SpeechEngine.stop();
    } catch (error) {
      console.error('停止朗读错误:', error);
    }
  };

  const pauseSpeaking = async (): Promise<void> => {
    try {
      await SpeechEngine.pause();
    } catch (error) {
      console.error('暂停朗读错误:', error);
    }
  };

  const resumeSpeaking = async (): Promise<void> => {
    try {
      await SpeechEngine.resume();
    } catch (error) {
      console.error('继续朗读错误:', error);
    }
  };

  return (
    <ScrollView style={styles.container}>
      <Text style={styles.title}>语音引擎示例 (TSX版)</Text>

      <View style={styles.section}>
        <Text style={styles.sectionTitle}>语音识别</Text>
        <Text style={styles.status}>
          状态: {isAvailable ? '可用' : '不可用'} | {isListening ? '正在监听...' : '未监听'}
        </Text>

        <View style={styles.buttonRow}>
          <TouchableOpacity
            style={[styles.button, isListening && styles.buttonActive]}
            onPress={startListening}
            disabled={isListening || !isAvailable}
          >
            <Text style={styles.buttonText}>开始识别</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.button}
            onPress={stopListening}
            disabled={!isListening}
          >
            <Text style={styles.buttonText}>停止识别</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.button}
            onPress={cancelListening}
            disabled={!isListening}
          >
            <Text style={styles.buttonText}>取消识别</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.textContainer}>
          <Text style={styles.label}>实时识别:</Text>
          <Text style={styles.partialText}>{partialText}</Text>

          <Text style={styles.label}>最终结果:</Text>
          <Text style={styles.recognizedText}>{recognizedText}</Text>
        </View>
      </View>

      <View style={styles.section}>
        <Text style={styles.sectionTitle}>文字转语音</Text>
        <Text style={styles.status}>
          状态: {isSpeaking ? '正在朗读...' : '未朗读'}
        </Text>

        <View style={styles.buttonRow}>
          <TouchableOpacity
            style={[styles.button, isSpeaking && styles.buttonActive]}
            onPress={() => speakText(recognizedText || '你好，这是语音合成测试')}
            disabled={isSpeaking}
          >
            <Text style={styles.buttonText}>开始朗读</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.button}
            onPress={pauseSpeaking}
            disabled={!isSpeaking}
          >
            <Text style={styles.buttonText}>暂停</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.button}
            onPress={resumeSpeaking}
            disabled={!isSpeaking}
          >
            <Text style={styles.buttonText}>继续</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.button}
            onPress={stopSpeaking}
            disabled={!isSpeaking}
          >
            <Text style={styles.buttonText}>停止</Text>
          </TouchableOpacity>
        </View>
      </View>

      <View style={styles.section}>
        <Text style={styles.sectionTitle}>快速测试</Text>
        <TouchableOpacity
          style={styles.testButton}
          onPress={() => speakText('你好，欢迎使用语音引擎')}
        >
          <Text style={styles.buttonText}>测试中文朗读</Text>
        </TouchableOpacity>

        <TouchableOpacity
          style={styles.testButton}
          onPress={() => speakText('Hello, welcome to speech engine')}
        >
          <Text style={styles.buttonText}>测试英文朗读</Text>
        </TouchableOpacity>
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 30,
    color: '#333',
  },
  section: {
    backgroundColor: 'white',
    padding: 20,
    marginBottom: 20,
    borderRadius: 10,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 3.84,
    elevation: 5,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 10,
    color: '#333',
  },
  status: {
    fontSize: 14,
    color: '#666',
    marginBottom: 15,
  },
  buttonRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    marginBottom: 15,
  },
  button: {
    backgroundColor: '#007AFF',
    paddingHorizontal: 15,
    paddingVertical: 10,
    borderRadius: 5,
    marginBottom: 10,
    minWidth: '30%',
  },
  buttonActive: {
    backgroundColor: '#FF3B30',
  },
  buttonText: {
    color: 'white',
    textAlign: 'center',
    fontSize: 14,
    fontWeight: '500',
  },
  textContainer: {
    marginTop: 10,
  },
  label: {
    fontSize: 14,
    fontWeight: '500',
    color: '#333',
    marginTop: 10,
    marginBottom: 5,
  },
  partialText: {
    fontSize: 16,
    color: '#666',
    fontStyle: 'italic',
    minHeight: 20,
  },
  recognizedText: {
    fontSize: 16,
    color: '#333',
    minHeight: 20,
    fontWeight: '500',
  },
  testButton: {
    backgroundColor: '#34C759',
    padding: 15,
    borderRadius: 5,
    marginBottom: 10,
  },
});

export default App;
